package com.example.Sao.MyActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.Sao.ObjectBox.DeviceEntity;
import com.example.Sao.R;
import com.example.Sao.Tools.ObjectBoxHelper;
import com.example.Sao.Tools.StatusColorUtil;
import com.google.gson.Gson;
import com.wang.avi.AVLoadingIndicatorView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class ChangeDeviceActivity extends MyBaseActivity implements View.OnClickListener{
    //控件
    private CardView back,iv_save;
    private ImageView iv_back,device_pic;
    private EditText area,floor,room,shelves;
    private TextView code,partment,device_id;
    //数据库实体bean
    private DeviceEntity deviceEntity;
    //数据库helper
    private ObjectBoxHelper objectBoxHelper;
    private static int REQUEST_CAMERA_2 = 2;
    private String mFilePath = Environment.getExternalStorageDirectory().getPath()+"/devicepic";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_device);
        //设置状态栏颜色
        StatusColorUtil.setColor(ChangeDeviceActivity.this,getResources().getColor(R.color.colorPrimary));
        //初始化控件
        initview();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取intent数据
        Intent intent = getIntent();
        //根据Json生成实体对象
        deviceEntity = new Gson().fromJson(intent.getStringExtra("devicemess"),DeviceEntity.class);
        //初始化数据库使用对象
        objectBoxHelper = ObjectBoxHelper.getInstance();
        //初始化页面数据
        initdata(deviceEntity);
    }

    /**控件监听
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //返回键
            case R.id.iv_back:
                //发出提醒Fragment
               showWarrAlertDialog();
                break;
            //返回键
            case R.id.back:
                //发出提醒Fragment
               showWarrAlertDialog();
                break;
            case R.id.iv_save:
                //保存数据对象
                SaveInfo(deviceEntity);
                break;
            case R.id.iv_device_pic:
                AlertDialog.Builder builder= new AlertDialog.Builder(ChangeDeviceActivity.this);
                builder.setMessage("是否开启拍照");
                builder.setTitle("提醒");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
                        startActivityForResult(intent, REQUEST_CAMERA_2);
                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;
            default:
                break;
        }
    }

    /**
     * 绑定控件
     */
    private void initview(){
        //绑定ID
        device_pic = findViewById(R.id.iv_device_pic);
        partment = findViewById(R.id.partment);
        device_id = findViewById(R.id.device_id);
        code = findViewById(R.id.code);
        back = findViewById(R.id.back);
        iv_save  =findViewById(R.id.iv_save);
        iv_back = findViewById(R.id.iv_back);
        area = findViewById(R.id.area);
        floor = findViewById(R.id.iv_floor);
        room  =findViewById(R.id.iv_room);
        shelves = findViewById(R.id.iv_shelves);
        //设置监听事件回调
        iv_back.setOnClickListener(this);
        back.setOnClickListener(this);
        iv_save.setOnClickListener(this);
        device_pic.setOnClickListener(this::onClick);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回数据
            if (requestCode == REQUEST_CAMERA_2) { // 判断请求码是否为REQUEST_CAMERA,如果是代表是这个页面传过去的，需要进行获取
                Bundle bundle = data.getExtras(); // 从data中取出传递回来缩略图的信息，图片质量差，适合传递小图片
                Bitmap bitmap = (Bitmap) bundle.get("data"); // 将data中的信息流解析为Bitmap类型
                device_pic.setImageBitmap(bitmap);// 显示图片
            }
        }
    }
    /**
     * 弹出提示窗
     */
    private void showWarrAlertDialog(){
        new SweetAlertDialog(ChangeDeviceActivity.this, SweetAlertDialog.WARNING_TYPE)
                //设置标题
                .setTitleText("提示")
                //设置提示信息
                .setContentText("退出后将无法保存填写的设备信息")
                //设置否定按钮
                .setCancelText("否")
                //设置确定按钮
                .setConfirmText("确定")
                //动态加入进度条View
                .AddLoading(new AVLoadingIndicatorView(getApplicationContext()))
                //设置确定按钮回调监听
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(final SweetAlertDialog sDialog) {
                        //关闭该Activity
                        ChangeDeviceActivity.this.finish();
                    }
                })
                //弹出
                .show();
    }

    /**
     * 弹出修改成功提示框
     */
    private void showsucces(){
        new SweetAlertDialog(ChangeDeviceActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                //设置标题
                .setTitleText("完成!")
                //设置提示信息
                .setContentText("修改数据已经更新到本地数据库!")
                //设置否定按钮
                .setCancelText("否")
                //设置确定按钮
                .setConfirmText("确定")
                //动态加入进度条View
                .AddLoading(new AVLoadingIndicatorView(getApplicationContext()))
                //设置确定按钮回调监听
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(final SweetAlertDialog sDialog) {
                        //关闭该Activity
                        ChangeDeviceActivity.this.finish();
                    }
                })
                .show();
    }

    /**
     * 保存修改后数据的业务
     */
    private void SaveInfo(DeviceEntity deviceEntity){
        //数据块实体对象为空就返回
        if (deviceEntity==null){
            return;
        }
        //修改信息判空
        if ((floor.getText().toString()!=""||floor.getText().toString()!=null)&&(room.getText().toString()!=""||room.getText().toString()!=null)
                &&(area.getText().toString()!=""||area.getText().toString()!=null)
                &&(shelves.getText().toString()!=""||shelves.getText().toString()!=null)){
            //移除该ID在数据库里对应的对象
            objectBoxHelper.remove(deviceEntity.getId());
            //设置新的数据参数
            deviceEntity.setLocationFloor(floor.getText().toString());
            deviceEntity.setLocationRoom(room.getText().toString());
            deviceEntity.setLocationPosition(area.getText().toString());
            deviceEntity.setLocationFloor(shelves.getText().toString());
            //添加该对象
             objectBoxHelper.add(deviceEntity);
             //弹出框展示时间
             new Handler().postDelayed(new Runnable() {
                 @Override
                 public void run() {
                     //弹出窗体
                     showsucces();
                 }
             },400);
        }else {
            Toast.makeText(this,"修改内容尚未填写完",Toast.LENGTH_LONG).show();
        }
    }

    /**初始化页面数据
     * @param deviceEntity
     */
    private void initdata(DeviceEntity deviceEntity){
        //设置UI文本
        code.setText(deviceEntity.getDeviceStreamCode());
        partment.setText("部门名称:"+deviceEntity.getUseDepartment());
        device_id.setText("设备名称:"+deviceEntity.getDeviceName());
        floor.setText(deviceEntity.getLocationFloor());
        room.setText(deviceEntity.getLocationRoom());
        area.setText(deviceEntity.getLocationPosition());
        shelves.setText(deviceEntity.getLocationIbm());
        //设置输入控件光标位置在最末尾
        area.setSelection(area.getText().toString().length());
        floor.setSelection(floor.getText().toString().length());
        room.setSelection(room.getText().toString().length());
        shelves.setSelection(shelves.getText().toString().length());
    }
}
